import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'core/dependency_injection.dart';
import 'core/api_client.dart';
import 'repositories/auth_repository_factory.dart';
import 'repositories/mood_repository_factory.dart';
import 'utils/auth_interceptor.dart';
import 'utils/auth_guard.dart';
import 'providers/auth_provider.dart';
import 'screens/splash_screen.dart';
import 'screens/timeline_screen.dart';
import 'screens/important_days_screen.dart';
import 'introduction_animation/introduction_animation_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initializeDateFormatting('zh_CN', null);

  // 配置Repository类型 - 可以在这里切换Mock或真实API
  AuthRepositoryFactory.setRepositoryType(
      AuthRepositoryType.mock); // 认证使用Mock模式进行测试
  MoodRepositoryFactory.setRepositoryType(RepositoryType.api); // 使用API模式

  // API模式下检查连接状态
  if (MoodRepositoryFactory.currentType == RepositoryType.api) {
    print('🔗 API模式已启用 - 连接到 http://localhost:8080');
    print('💡 如果后端服务未运行，应用会自动使用默认情话');
  }

  if (AuthRepositoryFactory.currentType == AuthRepositoryType.mock) {
    print('🔐 认证模式：Mock模式（测试用户：test@example.com/123456）');
  } else {
    print('🔐 认证模式：API模式');
  }

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initializeAuthInterceptor();
  }

  void _initializeAuthInterceptor() {
    // 创建认证拦截器，并设置Token过期回调
    final authInterceptor = AuthInterceptor(
      onTokenExpired: () {
        // Token过期时的处理逻辑
        final navigatorState = GlobalKey<NavigatorState>().currentState;
        if (navigatorState != null) {
          RouteGuard.handleTokenExpired(navigatorState.context);
        }
      },
    );

    // 设置认证拦截器到ApiClient
    ApiClient().setAuthInterceptor(authInterceptor);
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: DependencyInjection.providers,
      child: MaterialApp(
        title: '我们的小宇宙',
        theme: ThemeData(
          useMaterial3: true,
          colorScheme: ColorScheme.fromSeed(
            seedColor: const Color(0xFFFF6B9D),
            brightness: Brightness.light,
          ),
        ),
        home: const SplashScreen(), // 改为启动屏幕作为入口
        debugShowCheckedModeBanner: false,
        navigatorKey: GlobalKey<NavigatorState>(),
        // 路由生成器，用于处理受保护的路由
        onGenerateRoute: (settings) {
          switch (settings.name) {
            case '/':
            case '/timeline':
              return Auth.protectedRoute(
                (context) => const MyHomePage(),
                settings,
              );
            default:
              return MaterialPageRoute(
                builder: (context) => const SplashScreen(),
                settings: settings,
              );
          }
        },
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _currentIndex = 0;

  final List<Widget> _screens = [
    const TimelineScreen(),
    const ImportantDaysScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF3F4F6), // 浅灰背景
      body: SafeArea(
        child: Column(
          children: [
            // 顶部导航栏 - 优化设计
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.03),
                    blurRadius: 8,
                    offset: const Offset(0, 1),
                  ),
                ],
              ),
              child: Column(
                children: [
                  Container(
                    height: 60,
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: Row(
                      children: [
                        // 导航标签
                        Expanded(
                          child: Row(
                            children: [
                              _buildNavItem('📜', '时光轴', 0),
                              const SizedBox(width: 24),
                              _buildNavItem('✨', '重要日子', 1),
                            ],
                          ),
                        ),
                        // 右侧头像 - 添加点击事件
                        GestureDetector(
                          onTap: () {
                            _showProfileDrawer(context);
                          },
                          child: Container(
                            width: 36,
                            height: 36,
                            decoration: BoxDecoration(
                              color: const Color(0xFFFCE7F3),
                              borderRadius: BorderRadius.circular(18),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.08),
                                  blurRadius: 6,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: const Center(
                              child: Text('👩‍❤️‍👨',
                                  style: TextStyle(fontSize: 16)),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  // 分割线
                  Container(
                    height: 1,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Colors.transparent,
                          Colors.grey.withOpacity(0.2),
                          Colors.transparent,
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // 页面内容
            Expanded(
              child: _screens[_currentIndex],
            ),
          ],
        ),
      ),
    );
  }

  // 显示个人中心抽屉
  void _showProfileDrawer(BuildContext context) {
    Navigator.of(context).push(
      PageRouteBuilder(
        opaque: false,
        barrierDismissible: true,
        barrierColor: Colors.black54,
        pageBuilder: (context, animation, secondaryAnimation) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(CurvedAnimation(
              parent: animation,
              curve: Curves.easeOut,
            )),
            child: Align(
              alignment: Alignment.centerRight,
              child: Material(
                color: Colors.transparent,
                child: SafeArea(
                  child: Container(
                    height: MediaQuery.of(context).size.height,
                    width: MediaQuery.of(context).size.width * 0.85,
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(20),
                        bottomLeft: Radius.circular(20),
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black26,
                          blurRadius: 10,
                          offset: Offset(-5, 0),
                        ),
                      ],
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 头部区域
                        Container(
                          padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                              colors: [
                                Colors.pink.shade50,
                                Colors.pink.shade100
                              ],
                            ),
                          ),
                          child: Row(
                            children: [
                              Container(
                                width: 60,
                                height: 60,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(30),
                                  border: Border.all(
                                      color: Colors.pink.shade200, width: 2),
                                ),
                                child: const Center(
                                  child: Text('👩‍❤️‍👨',
                                      style: TextStyle(fontSize: 30)),
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text(
                                      '我们的小宇宙',
                                      style: TextStyle(
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.black87,
                                      ),
                                    ),
                                    const SizedBox(height: 4),
                                    Text(
                                      '在一起 365 天',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.pink.shade700,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              IconButton(
                                onPressed: () => Navigator.pop(context),
                                icon: const Icon(Icons.close),
                                color: Colors.grey.shade700,
                              ),
                            ],
                          ),
                        ),

                        // 功能列表
                        Expanded(
                          child: ListView(
                            padding: const EdgeInsets.all(0),
                            children: [
                              _buildProfileMenuItem(
                                icon: Icons.settings,
                                title: '设置',
                                subtitle: '个性化、通知、隐私',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('设置功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.color_lens,
                                title: '主题与外观',
                                subtitle: '自定义应用颜色和风格',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('主题功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.backup,
                                title: '备份与恢复',
                                subtitle: '保存和恢复重要数据',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('备份功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.notifications,
                                title: '提醒设置',
                                subtitle: '重要日子和纪念日提醒',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('提醒功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.photo_album,
                                title: '相册管理',
                                subtitle: '管理共同的照片和回忆',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('相册功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.favorite,
                                title: '情侣互动',
                                subtitle: '特殊互动和小惊喜',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('互动功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.help,
                                title: '帮助与反馈',
                                subtitle: '常见问题和意见反馈',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('帮助功能即将上线')),
                                  );
                                },
                              ),
                              _buildProfileMenuItem(
                                icon: Icons.info,
                                title: '关于',
                                subtitle: '版本信息和开发者',
                                onTap: () {
                                  Navigator.pop(context);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('关于信息即将上线')),
                                  );
                                },
                              ),

                              // 添加分隔线
                              const Divider(height: 32),

                              // 登出按钮
                              Consumer<AuthProvider>(
                                builder: (context, authProvider, child) {
                                  return _buildProfileMenuItem(
                                    icon: Icons.logout,
                                    title: '退出登录',
                                    subtitle: '安全退出当前账号',
                                    onTap: () async {
                                      Navigator.pop(context);

                                      // 显示确认对话框
                                      final confirmed = await showDialog<bool>(
                                        context: context,
                                        builder: (context) => AlertDialog(
                                          title: const Text('确认退出'),
                                          content: const Text('您确定要退出登录吗？'),
                                          actions: [
                                            TextButton(
                                              onPressed: () =>
                                                  Navigator.pop(context, false),
                                              child: const Text('取消'),
                                            ),
                                            TextButton(
                                              onPressed: () =>
                                                  Navigator.pop(context, true),
                                              style: TextButton.styleFrom(
                                                foregroundColor: Colors.red,
                                              ),
                                              child: const Text('退出'),
                                            ),
                                          ],
                                        ),
                                      );

                                      if (confirmed == true) {
                                        await RouteGuard.handleLogout(context);
                                      }
                                    },
                                  );
                                },
                              ),
                            ],
                          ),
                        ),

                        // 底部版本信息
                        Container(
                          padding: const EdgeInsets.all(16),
                          alignment: Alignment.center,
                          child: Text(
                            '版本 1.0.0',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade500,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // 构建个人中心菜单项
  Widget _buildProfileMenuItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: Colors.pink.shade50,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(icon, color: Colors.pink.shade400, size: 20),
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontWeight: FontWeight.w600,
          fontSize: 16,
        ),
      ),
      subtitle: Text(
        subtitle,
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey.shade600,
        ),
      ),
      trailing: Icon(Icons.chevron_right, color: Colors.grey.shade400),
      onTap: onTap,
    );
  }

  Widget _buildNavItem(String icon, String title, int index) {
    final isSelected = _currentIndex == index;
    return GestureDetector(
      onTap: () {
        setState(() {
          _currentIndex = index;
        });
      },
      child: Container(
        height: 60,
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 图标和文字
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(icon, style: const TextStyle(fontSize: 15)),
                const SizedBox(width: 5),
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                    color: isSelected
                        ? const Color(0xFF1F2937)
                        : const Color(0xFF6B7280),
                  ),
                ),
              ],
            ),
            // 底部指示线
            const SizedBox(height: 6),
            AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              height: 2,
              width: isSelected ? (title.length * 8.0) + 20 : 0,
              decoration: BoxDecoration(
                color: const Color(0xFFF472B6),
                borderRadius: BorderRadius.circular(1),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
